<?php
/**
 *  公告
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-10-20
 * Time: 14:38
 */

namespace App\Http\Controllers\Api\V1\Manager\System;


use App\Http\Controllers\Controller;
use App\Models\Notice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class NoticeController extends Controller
{
    public function index(Request $request)
    {
        $pageSize = $request->pageSize ? $request->pageSize : 20;
        $keyWords = $request->keyWords;
        $sql = Notice::select('noticeId', 'noticeTitle', 'createTime','noticeDetail');
        if ($keyWords) {
            $sql->where('noticeTitle', 'like', '%' . $keyWords . '%');
        }
        $data = $sql->orderBy('createTime', 'DESC')->paginate($pageSize)->toArray();
        $result['noticeList'] = $data['data'];
        $result['totalNum'] = $data['total'];
        return $this->apiResponse($result);
    }

    public function show($noticeId)
    {
        $data = Notice::find($noticeId);
        return $this->apiResponse($data);
    }

    public function store(Request $request)
    {
        $data = $request->only(['noticeId', 'noticeTitle', 'noticeDetail']);
        $validator = Validator::make($data, [
            "noticeId" => "integer",
            "noticeTitle" => "required",
            "noticeDetail" => "required"
        ]);
        if ($validator->fails()) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $noticeId = $data['noticeId'];
        unset($data['noticeId']);
        if($noticeId){
            $status = Notice::where('noticeId',$noticeId)->update($data);
        }else{
            $status = Notice::create($data);
        }
        if(!$status){
            return $this->apiResponse('', config('errorCode.UPDATE_FAILED'));
        }
        return $this->apiResponse('');
    }
    public function destroy($noticeId)
    {
        Notice::destroy($noticeId);
        return $this->apiResponse('');
    }
}